# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '69019018087601': {  # 旺实付支付  支付宝H5 10-20000 2.8% DWC
        'API_KEY': '04690920353446zR2wit',
        'gateway': 'http://tojrewk.paywap.cn/jh-web-order/order/receiveOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(d, key):
    s = '{}&{}&{}&{}&{}&{}'.format(
        d['p1_yingyongnum'], d['p2_ordernumber'],
        d['p3_money'], d['p6_ordertime'],
        d['p7_productcode'], key)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = '{}&{}&{}&{}&{}&{}&{}&{}&{}&{}&{}'.format(
        d['p1_yingyongnum'], d['p2_ordernumber'],
        d['p3_money'], d['p4_zfstate'],
        d['p5_orderid'], d['p6_productcode'], d['p7_bank_card_code'], d['p8_charset'], d['p9_signtype'], d['p11_pdesc'],
        key)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['p10_sign']
    params.pop('p10_sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("wangshifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipayh5':
        return 'ZFB'
    return 'ZFB'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def get_phone_type(info):
    if 'android' in info.get('sdk_version', ''):
        # 1-pc 2-iOS 3-Android
        return '3'
    else:
        return '2'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('p1_yingyongnum', app_id),
        ('p2_ordernumber', str(pay.id)),
        ('p3_money', '%.2f' % pay_amount),
        ('p6_ordertime', local_now().strftime('%Y%m%d%H%M%S')),
        ('p7_productcode', _get_pay_type(service)),
        ('p14_customname', pay.user_id),
        ('p16_customip', _get_device_ip(info)),
        ('p25_terminal', get_phone_type(info)),
    ))
    parameter_dict['p8_sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("wangshifupay create: %s, order_id is:%s ", json.dumps(parameter_dict),
                 parameter_dict['p2_ordernumber'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('wangshifupay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("wangshifupay notify data: %s, order_id is: %s", data, data['p2_ordernumber'])
    verify_notify_sign(data, api_key)
    pay_id = data['p2_ordernumber']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('wangshifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['p4_zfstate'])
    trade_no = data['p5_orderid']
    total_fee = float(data['p13_zfmoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('wangshifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
